import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { NavController, NavParams, ToastController } from 'ionic-angular';
import { ScanPage } from '../scan/scan';
// import { AlarmPage } from '../alarm/alarm';


/**
 * Generated class for the ValidatePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-validate',
  templateUrl: 'validate.html',
})
export class ValidatePage {
  group: FormGroup;

  timer = 120;
  timerTick: any;
  source: any;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private builder: FormBuilder,
              private toastCtrl: ToastController,
              private translate: TranslateService,
              private rest: RestService) {
    this.group = this.builder.group({
      // username: [ '', [ Validators.required, Validators.minLength(11), Validators.maxLength(16), Validators.pattern('[\+0-9]+') ] ],
      username: navParams.data.person.personName,
      vcode: [ '', [ Validators.required, Validators.minLength(4), Validators.maxLength(4), Validators.pattern('[0-9]+') ] ],
      password: [ '', [ Validators.required ] ]
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ValidatePage');
  }

  navBack() {
    this.navCtrl.pop();
  }

  doValidate(action) {
    this.rest.post('/api/keycloak/validateCode', {
      phoneNumber: this.group.controls.username.value,
      code: this.group.controls.vcode.value
    }).subscribe(resp => {
      if (resp.status >= 200 && resp.status < 300) {
        this.rest.saveUser({
          username: this.group.controls.username.value,
          password: this.group.controls.password.value,
          locale: '',
          role: ''
        });
        this.rest.validated = true;
        this.navBack();
      } else {
        if (resp.status === 406) {
          this.showToast(this.translate.get('codeMismatch')['value']);
        } else {
          this.showToast(this.translate.get('badRequest')['value']);
        }
      }
    }, error => {
      this.showToast(this.translate.get('badRequest')['value']);
      console.error('Failed to validate user!');
    });
  }

  showToast(message) {
    const toast = this.toastCtrl.create({
      message: message,
      duration: 5000,
      position: 'bottom'
    });

    toast.present(toast);
  }

  getVerificationCode() {
    if (this.timer !== 120) {
      return;
    }

    this.startTick();

    this.rest.getValidateCode(this.group.controls.username.value).subscribe(resp => {
      if (resp.status !== 200) {
        console.error('Failed to get code: ' + resp.info);
        if (resp.info) {
          this.showToast(resp.info);
        }
        this.stopTick();
      }
    }, error => {
      console.error('Failed to get code' + error);
      this.showToast(this.translate.get('badRequest')['value']);
      this.stopTick();
    });
  }

  getCodeText() {
    if (this.timer === 120) {
      return this.translate.get('getCode')['value'];
    } else {
      return this.timer + this.translate.get('waitCode')['value'];
    }
  }

  stopTick() {
    if (this.timerTick) {
      clearInterval(this.timerTick);
      this.timer = 120;
    } else {
      this.timer = 120;
    }
  }

  startTick() {
    this.timer = 99;

    this.timerTick = setInterval(() => {
      if (this.timer <= 1) {
        this.timer = 120;
        if (this.timerTick) {
          clearInterval(this.timerTick);
        }
      } else {
        this.timer--;
      }
    }, 1000);
  }

}
